package controllers

import (
	"github.com/gin-gonic/gin"
	models "jjqzplucky.site/sz-core/internal/models/mis_user"
	"jjqzplucky.site/sz-core/pkg/constants"
	"jjqzplucky.site/sz-core/pkg/utils/token"
)

// ReqRegister /api/register的请求体
type ReqRegister struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type ReqLogin struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type AuthController struct{}

// Register 用户注册
func (a *AuthController) Register(c *gin.Context) {
	var req ReqRegister
	if err := c.ShouldBindBodyWithJSON(&req); err != nil {
		c.Error(err)
		return
	}

	u := models.MisUser{
		Username: req.Username,
		Password: req.Password,
	}

	user, err := u.SaveUser()
	if err != nil {
		c.Error(err)
		return
	}

	c.Set(constants.ResultData, user)
}

func (a *AuthController) Login(c *gin.Context) {
	var req ReqRegister
	if err := c.ShouldBindBodyWithJSON(&req); err != nil {
		c.Error(err)
		return
	}

	u := models.MisUser{
		Username: req.Username,
		Password: req.Password,
	}

	// 调用 models.LoginCheck 对用户名和密码进行验证
	token, err := models.LoginCheck(u.Username, u.Password)
	if err != nil {
		c.Error(err)
		return
	}
	c.Set(constants.ResultData, token)
}

func CurrentUser(c *gin.Context) {
	// 从token中解析出user_id
	user_id, err := token.ExtractTokenID(c)
	if err != nil {
		c.Error(err)
		return
	}

	// 根据user_id从数据库查询数据
	u, err := models.GetUserByID(user_id)
	if err != nil {
		c.Error(err)
		return
	}
	c.Set(constants.ResultData, u)
}
